/**
 * Created with IntelliJ IDEA.
 * Description:链表相加（二）
 * User: wangxin
 * Date: 2024-10-24
 * Time: 23:06
 */
import java.util.*;


  class ListNode {
    int val;
    ListNode next = null;
   public ListNode(int val) {
      this.val = val;
    }
  }


public class test {
    public  ListNode ReverstList(ListNode head){
        if(head == null){
            return null;
        }
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        head1 = ReverstList(head1);
        head2 = ReverstList(head2);
        ListNode res = new ListNode(-1);
        ListNode head = res;
        int carry = 0;
        while(head1 != null||head2 != null||carry != 0){
            int t1 = head1 == null ? 0: head1 .val;
            int t2 = head2 == null ? 0: head2 .val;
            int t = t1 + t2 + carry;
            carry = t / 10;
            t = t % 10;
            head.next = new ListNode(t);
            head = head.next;
            if(head1 != null){
                head1 = head1.next;
            }
            if(head2 != null){
                head2 = head2.next;
            }
        }
        return ReverstList(res.next);
    }
}
